package com.yf.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.Utils.CacheKey;
import com.yf.Utils.FileUtil;
import com.yf.Utils.RedisUtils;
import com.yf.dao.JobMapper;
import com.yf.dao.UserMapper;
import com.yf.domain.security.Job;
import com.yf.model.query.JobQueryCriteria;
import com.yf.modules.system.service.api.JobService;
import com.yf.response.exceptions.BusinessException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

/**
 * @author chentianwei
 * @date 2024-10-29 12:49
 * @description 岗位业务实现层
 */
@Service
@Slf4j
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    private final JobMapper jobMapper;
    private final UserMapper userMapper;
    private final RedisUtils redisUtils;

    public JobServiceImpl(JobMapper jobMapper,
                          UserMapper userMapper,
                          RedisUtils redisUtils) {
        this.jobMapper = jobMapper;
        this.userMapper = userMapper;
        this.redisUtils = redisUtils;
    }

    /**
     * 根据ID查询
     *
     * @param id /
     * @return /
     */
    @Override
    public Job findById(Long id) {
        return null;
    }

    /**
     * 创建
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Job resources) {
        if (ObjectUtil.isNotEmpty(resources.getId())) {
            throw new BusinessException("新创建的职务已有ID值,请检查!");
        }
        if (ObjectUtil.isNotNull(jobMapper.findByName(resources.getName()))) {
            throw new BusinessException("职位名称:" + resources.getName() + "已存在,无法重复添加");
        }
        save(resources);
    }

    /**
     * 编辑
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Job resources) {
        Job job = getById(resources.getId());
        Job old = jobMapper.findByName(resources.getName());
        if (old != null && !old.getId().equals(resources.getId())) {
            throw new BusinessException("职位名称：" + resources.getName() + "重复存在，请检查");
        }
        resources.setId(job.getId());
        saveOrUpdate(resources);
    }

    /**
     * 删除
     *
     * @param ids /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        //检查是否关联了用户
        verification(ids);
        //Batch删除
        removeBatchByIds(ids);
        // 删除缓存
        redisUtils.delByKeys(CacheKey.JOB_ID, ids);
    }

    /**
     * 查询全部数据
     *
     * @param criteria /
     * @return /
     */
    @Override
    public List<Job> queryAll(JobQueryCriteria criteria) {
        return jobMapper.findAll(criteria);
    }

    /**
     * 导出数据
     *
     * @param criteria 查询条件
     * @param response /
     * @throws IOException /
     */
    @Override
    public void download(JobQueryCriteria criteria, HttpServletResponse response) throws IOException {
        List<Job> jobs = queryAll(criteria);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Job job : jobs) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("岗位名称", job.getName());
            map.put("岗位状态", job.getEnabled() ? "启用" : "停用");
            map.put("创建日期", job.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 验证是否被用户关联
     *
     * @param ids /
     */
    @Override
    public void verification(Set<Long> ids) {
        if (userMapper.countByJobs(ids) > 0) {
            throw new BusinessException("所选的岗位中存在用户关联，请解除关联再试！");
        }
    }
}
